//
//  YBSearchController.m
//  Cocoachina
//
//  Created by 游兵 on 2017/9/14.
//  Copyright © 2017年 YBing. All rights reserved.
//

#import "YBSearchController.h"
#import "YBNews.h"
#import "YBSearchCell.h"
#import "UITableViewCell+YB.h"
#import "YBNewsDetailController.h"
#import <MJRefresh.h>

@interface YBSearchController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITextField *searchTF;

@property (nonatomic, strong) NSMutableArray<YBNews *> *datas;
@property (nonatomic, assign) NSInteger page;

@end

@implementation YBSearchController

- (IBAction)cancelClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self.searchTF becomeFirstResponder];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setupUI
{
    self.navView.backgroundColor = kNavColor;
    self.searchTF.tintColor = kNavColor;
    self.searchTF.enablesReturnKeyAutomatically = YES;
    self.tableView.estimatedRowHeight = 64;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    YBWeakSelf
    kSetupRefreshNormalHeader
}

- (void)loadData
{
    NSString *url = [NSString stringWithFormat:@"http://www.cocoachina.com/cms/plus/search.php?keyword=%@&searchtype=titlekeyword&channeltype=0&orderby=&kwtype=0&pagesize=10&typeid=0&TotalResult=3781&PageNo=%zi", self.searchTF.text, 1];
    [YBHttpTool get:url success:^(TFHpple *doc) {
        [self.tableView.mj_header endRefreshing];
        NSMutableArray *datas = [self parseWithHpple:doc];
        self.datas = datas;
        YBWeakSelf
        if (self.tableView.mj_footer==nil) {
            self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                [weakSelf loadMoreData];
            }];
        }
        if (datas.count==0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer resetNoMoreData];
        }
        self.page = 2;
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData
{
    NSString *url = [NSString stringWithFormat:@"http://www.cocoachina.com/cms/plus/search.php?keyword=%@&searchtype=titlekeyword&channeltype=0&orderby=&kwtype=0&pagesize=10&typeid=0&TotalResult=3781&PageNo=%zi", self.searchTF.text, self.page];
    [YBHttpTool get:url success:^(TFHpple *doc) {
        [self.tableView.mj_footer endRefreshing];
        NSMutableArray *datas = [self parseWithHpple:doc];
        [self.datas addObjectsFromArray:datas];
        if (datas.count==0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            self.page++;
            [self.tableView.mj_footer resetNoMoreData];
        }
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (NSMutableArray<YBNews *> *)parseWithHpple:(TFHpple *)doc
{
    TFHppleElement *element  = [[doc searchWithXPathQuery:@"//div[@class='leftSide float-l']"] firstObject];
    TFHppleElement *div = [element childrenWithTagName:@"div"][1];
    
    NSArray<TFHppleElement *> *list = [[div firstChildWithTagName:@"ul"] childrenWithTagName:@"li"];
    NSMutableArray *datas = [NSMutableArray array];
    [list enumerateObjectsUsingBlock:^(TFHppleElement * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YBNews *news = [YBNews new];
        news.url = [[[obj firstChildWithTagName:@"div"] firstChildWithTagName:@"a"] objectForKey:@"href"];
        TFHppleElement *a = [[obj firstChildWithTagName:@"div"] firstChildWithTagName:@"a"];
        NSMutableString *title = [NSMutableString string];
        [[a children] enumerateObjectsUsingBlock:^(TFHppleElement * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.isTextNode) {
                [title appendString:obj.content];
            } else {
                [title appendString:obj.raw];
            }
        }];
        news.title = title;
        news.desc = ((TFHppleElement *)[obj childrenWithTagName:@"div"][1]).raw;
        
        news.time = [[[[obj childrenWithTagName:@"div"] lastObject] firstChildWithClassName:@"float-l"] firstChildWithTagName:@"span"].text;
        news.readnum = [[[[[obj childrenWithTagName:@"div"] lastObject] firstChildWithClassName:@"float-l"] childrenWithTagName:@"span"] lastObject].text;
        [datas addObject:news];
        
    }];
    return datas;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBSearchCell *cell = [YBSearchCell cellWithTableView:tableView];
    cell.news = self.datas[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YBNewsDetailController *vc = [YBNewsDetailController new];
    vc.url = [NSString stringWithFormat:@"%@%@", @"http://www.cocoachina.com/", self.datas[indexPath.row].url];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_header beginRefreshing];
    [textField resignFirstResponder];
    return YES;
}


@end
